package server;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.ArrayList;

import org.apache.log4j.Logger;

import serverhelper.ServerHelper;
import api.messages.Messager;

public class ServerThread extends Thread {

	private ObjectOutputStream objectWriter;
	private ObjectInputStream objectReader;
	private ServerHelper server_helper = ServerHelper.getInstance();
	private ArrayList<String> clientRequest = new ArrayList<String>();
	private Socket s;
	private Logger log=Logger.getLogger(ServerThread.class);

	public ServerThread(Socket s) {
		this.s = s;
		try {
			objectWriter = new ObjectOutputStream(s.getOutputStream());
			objectReader = new ObjectInputStream(s.getInputStream());
		} catch (IOException e) {
			System.out.println(Messager.EXCEPTION_SERVER_THREAD);
			log.fatal(Messager.EXCEPTION_SERVER_THREAD);
		}
	}

	public void run() {
		try {
			while (true) {
				clientRequest.clear();
				clientRequest.addAll((ArrayList<String>) objectReader.readObject());			
				ArrayList<String> serverAnswer=new ArrayList<String>();
				serverAnswer.addAll(server_helper.getServerAnswer(clientRequest));
				objectWriter.writeObject(serverAnswer);			
				
			}

		} catch (SocketTimeoutException e) {
			try {
				System.out.println(" disconnected");
				objectWriter.close();
				objectReader.close();
			} catch (IOException ei) {
				e.printStackTrace();
				log.error(e);
			}

		} catch (IOException e) {
			System.out.println("Disconnect");
			log.error(e);
		} catch (ClassNotFoundException e) {
			System.out.println(Messager.EXCEPTION_SERVER_THREAD);
			log.warn(Messager.EXCEPTION_SERVER_THREAD);
		} finally {
			disconnect();
		}
	}

	public void disconnect() {
		try {
			System.out.println(" disconnected");
			s.close();
			objectWriter.close();
			objectReader.close();
		} catch (IOException e) {
			e.printStackTrace();
			log.fatal(e);
		} finally {
			this.interrupt();
		}
	}

}
